package com.aabte.design.pattern.creational.singleton;

/**
 * 懒汉模式之双重判断
 */
public class LazySingleton {

    private static LazySingleton instance = null;

    private LazySingleton(){
        if (instance != null) {
            throw new RuntimeException("单例构造器禁止反射调用！");
        }
    }

    /**
     * synchronized加在静态方法上，锁的是类
     * synchronized加在实例方法上，锁的是对象
     */
    public synchronized static LazySingleton getInstance(){
        if (null == instance) {
            instance = new LazySingleton();
        }
        return instance;
    }

    public static LazySingleton getInstance2(){
        synchronized (LazySingleton.class) {
            if (null == instance) {
                instance = new LazySingleton();
            }
        }
        return instance;
    }

}
